//
//  LGAddInspectReportController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/2.
//  新增检验检查报告

#import "LGAddInspectReportController.h"
//新增异常指标
#import "LGAddAnomalyNormController.h"
#import "LGAddReportHeaderView.h"
#import "LGInspectionAnomalyCell.h"
#import "LGPickerView.h"
#import "LGNavigationController.h"
@interface LGAddInspectReportController ()<UITableViewDelegate,UITableViewDataSource,LGInspectionAnomalyDelegate,LGAddReportHeaderViewDelegate>
/**   */
@property (nonatomic , strong)LGAddReportHeaderView *headView;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIView *bottomView;
/**   */
@property (nonatomic , strong)UIButton *saveBtn;
/**   */
@property (nonatomic , strong)UIButton *deleteBtn;
/**   */
@property (nonatomic , strong)NSArray *typeArray;
/**   */
@property (nonatomic , strong)NSArray *pickerArray;
/**   */
@property (nonatomic , strong)NSMutableArray *dataArray;
/**   */
@property (nonatomic , strong)NSMutableArray *photoArray;
/**   */
@property (nonatomic , copy)NSString *idString;
/**   */
@property (nonatomic , copy)NSString *codeString;
@end

@implementation LGAddInspectReportController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationView.title = @"新增检验检查报告";
    CGFloat leftMargin = (_reportid && _reportid.length>0)?(Screen_W-viewPix(45))/2.0+viewPix(26):viewPix(17);
    CGFloat saveWidth = (_reportid && _reportid.length>0)?(Screen_W-viewPix(45))/2.0:Screen_W-viewPix(34);
    self.saveBtn.frame = CGRectMake(leftMargin, viewPix(12), saveWidth, viewPix(46));
    if(_reportid && _reportid.length>0){
        //编辑
        self.navigationView.title = @"编辑检验检查报告";
        self.saveBtn.frame = CGRectMake((Screen_W-viewPix(45))/2.0+viewPix(26), viewPix(12), (Screen_W-viewPix(45))/2.0, viewPix(46));
        self.deleteBtn.hidden = NO;
        [self requestData];
    }else{
        self.reportid = @"";
        self.saveBtn.frame = CGRectMake(viewPix(17), viewPix(12), Screen_W-viewPix(34), viewPix(46));
        self.deleteBtn.hidden = YES;
    }
    [self createSubView];
    [self requestTypeList];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [LGNavigationController initialize];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/Visitrecords/inspectionDetail" parameters:@{@"record_id":self.reportid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.headView.dateTF.text = LGNSString(returnData[@"exams_date"]);
            NSString *exam_code = LGNSString(returnData[@"exams_code"]);
            for (NSDictionary *tempDic in returnData[@"report_types"]) {
                if([tempDic[@"code"] isEqualToString:exam_code]){
                    self.headView.programTF.text = LGNSString(tempDic[@"title"]);
                    self.codeString = LGNSString(tempDic[@"code"]);
                    self.idString = LGNSString(tempDic[@"id"]);
                    break;
                }
            }
            self.headView.photoView.urlArray = returnData[@"weburls"];
            self.dataArray = [NSMutableArray arrayWithArray:[ObjectTool jsonToObject:returnData[@"unusual_list_json"]]];
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

//请求项目列表
-(void)requestTypeList{
    [RequestUtil withPOST:@"/doctor/other.inspection_report_type/typeList" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.typeArray = returnData[@"list"];
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSInteger i=0; i<self.typeArray.count; i++) {
                NSDictionary *tempDic = self.typeArray[i];
                [tempArray addObject:LGNSString(tempDic[@"title"])];
            }
            self.pickerArray = [NSArray arrayWithArray:tempArray];
        }
    } error:^(NSError *error) {
        
    }];
}


-(void)headViewHeightChanged:(CGFloat)height{
    self.headView.frame = CGRectMake(0, 0, Screen_W, height);
    self.tableView.tableHeaderView = self.headView;
}

//选择检查项目
-(void)selectInspectItemAction{
    if(self.pickerArray.count == 0){
        [self requestTypeList];
        return;
    }
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = @[self.pickerArray];
    pickerView.selectStr = self.headView.programTF.text;
    [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        weakSelf.headView.programTF.text = LGNSString(resultArray[0]);
        for (NSDictionary *tempDic in weakSelf.typeArray) {
            if([LGNSString(resultArray[0]) isEqualToString:tempDic[@"title"]]){
                weakSelf.idString = LGNSString(tempDic[@"id"]);
                weakSelf.codeString = LGNSString(tempDic[@"code"]);
            }
        }
    };
}

//新增指标
-(void)addAnomalyAction{
    if(self.headView.programTF.text.length == 0){
        [TooltipView showMessage:@"请先选择检查项目" offset:0];
        return;
    }
    LGAddAnomalyNormController *controller = [[LGAddAnomalyNormController alloc]init];
    controller.normid = self.idString;
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.addAnomalyNormSuccess = ^(NSDictionary * _Nonnull dataDic) {
        [weakSelf.dataArray addObject:dataDic];
        [weakSelf.tableView reloadData];
    };
    
}

//编辑异常指标
-(void)editAnomalyNorm:(NSInteger)index{
    LGAddAnomalyNormController *controller = [[LGAddAnomalyNormController alloc]init];
    controller.dataDic = self.dataArray[index];
    controller.normid = self.idString;
    controller.index = index;
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.editAnomalyNormFinished = ^(NSDictionary * _Nonnull dataDic, NSInteger index) {
        [weakSelf.dataArray replaceObjectAtIndex:index withObject:dataDic];
        [weakSelf.tableView reloadData];
    };
}

//删除异常指标
-(void)deleteAnomalyNorm:(NSInteger)index{
    if(index<self.dataArray.count){
        NSString *content = [NSString stringWithFormat:@"您确定要删除%@吗？",self.dataArray[index][@"entry_name"]];
        __block NSInteger deleteIndex = index;
        __weak typeof(self) weakSelf = self;
        [LGAlertTool alertWithTitle:@"删除异常指标" content:content sureAction:^{
            [weakSelf.dataArray removeObjectAtIndex:deleteIndex];
            [weakSelf.tableView reloadData];
        }];
        
    }else{
        [TooltipView showMessage:@"删除异常" offset:0];
    }
}


//保存
-(void)saveBtnAction{
    if(self.headView.dateTF.text.length == 0){
        [TooltipView showMessage:@"请选择日期" offset:0];
        return;
    }
    if(self.headView.programTF.text.length == 0){
        [TooltipView showMessage:@"请选择检查项目" offset:0];
        return;
    }
    if(self.headView.photoView.allImageArray.count == 0){
        [TooltipView showMessage:@"请上传报告图片" offset:0];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [RequestUtil uploadImage:@"/doctor/upload/image" parameters:@{} withSign:YES indexName:@"photo[]" imageArray:self.headView.photoView.allImageArray success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            NSArray *dataArray = returnData;
            NSMutableArray *photoArray = [NSMutableArray array];
            for (NSDictionary *tempDic in dataArray) {
                [photoArray addObject:LGNSString(tempDic[@"uri"])];
            }
            [RequestUtil withPOST:@"/doctor/Visitrecords/inspectionSave" parameters:@{@"patient_id":self.patientid,@"record_id":self.reportid,@"durls":photoArray,@"exams_date":self.headView.dateTF.text,@"exams_code":self.codeString,@"unusual_list_json":[ObjectTool objectToJson:self.dataArray]} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if(code == 200){
                    [TooltipView showMessage:@"保存成功" offset:0];
                    if(self.addReportSuccess){
                        self.addReportSuccess();
                    }
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [TooltipView showMessage:message offset:0];
                }
            } error:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }else{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

//删除
-(void)deleteBtnAction{
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:@"确定要删除此报告吗 ？" sureAction:^{
        [RequestUtil withPOST:@"/doctor/Visitrecords/inspectionDel" parameters:@{@"record_id":weakSelf.reportid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                if(weakSelf.addReportSuccess){
                    weakSelf.addReportSuccess();
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"删除失败，请重试" offset:0];
        }];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGInspectionAnomalyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.dataArray[indexPath.row];
    cell.index = indexPath.row;
    cell.delegate = self;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(48);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LGCornerHeaderView *headView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(48))];
    headView.topMargin = viewPix(8);
    
    UILabel *titleLabel = [UILabel lableWithText:@"异常指标" colorString:@"#333333" textFont:LGFontWeight(15, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    titleLabel.frame = CGRectMake(viewPix(32), viewPix(20), viewPix(100), viewPix(20));
    [headView addSubview:titleLabel];
    UIButton *addButton = [UIButton buttonWithTitle:@"  新增" titleFont:LGFontWeight(15, UIFontWeightMedium) textColor:@"#429BFF" imageName:@"报告指标-新增"];
    addButton.frame = CGRectMake(Screen_W-viewPix(90), viewPix(15), viewPix(70), viewPix(30));
    [addButton addTarget:self action:@selector(addAnomalyAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:addButton];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = (self.dataArray.count>0)?viewPix(15):viewPix(60);
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = (self.dataArray.count>0)?viewPix(15):viewPix(60);
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    footView.bottomMargin = viewPix(8);
    return footView;
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.saveBtn];
    [self.bottomView addSubview:self.deleteBtn];
}

-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight-viewPix(84)-bottomSafeBarHeight/4.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGInspectionAnomalyCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = self.headView;
    }
    return _tableView;
}

-(LGAddReportHeaderView *)headView{
    if(!_headView){
        _headView = [[LGAddReportHeaderView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(310))];
        _headView.delegate = self;
    }
    return _headView;
}

-(UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(84)+bottomSafeBarHeight/4.0)];
    }
    return _bottomView;
}

-(UIButton *)saveBtn{
    if(!_saveBtn){
        _saveBtn = [UIButton buttonWithTitle:@"保存" topMargin:viewPix(12)];
        [_saveBtn addTarget:self action:@selector(saveBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}

-(UIButton *)deleteBtn{
    if(!_deleteBtn){
        _deleteBtn = [UIButton buttonWithTitle:@"删除" titleFont:LGFontWeight(16, UIFontWeightSemibold) normalColor:@"#DD3030" selectColor:@"#DD3030"];
        _deleteBtn.frame = CGRectMake(viewPix(17), viewPix(12), (Screen_W-viewPix(45))/2.0, viewPix(46));
        _deleteBtn.layer.borderColor = [UIColor colorWithString:@"#DD3030"].CGColor;
        _deleteBtn.layer.borderWidth = 1.0;
        _deleteBtn.layer.cornerRadius = 10;
        _deleteBtn.hidden = YES;
        [_deleteBtn addTarget:self action:@selector(deleteBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
